#!/usr/bin/env python

from collections import defaultdict
from news_class import News

def init ( l, admin = 0 ):
	from liwe import parts

	News ( l )

	try:
		admin = int ( admin, 10 )
	except:
		admin = 0

	parts.add ( l.layman, [ "form" ] )
	parts.add_wwl ( l.layman, [ "tabs" ] )

	l.layman.add_js ( "modules/news/js/news.js" )
	l.layman.add_css ( "modules/news/gfx/news.css" )

	if admin:
		parts.add_wwl ( l.layman, [ "calendar", "jconed" ] )
		parts.add ( l.layman, [ "ext" ] )

		l.layman.add_css ( "modules/news/gfx/news.admin.css" )
		l.layman.add_js ( "modules/news/js/news.admin.js" )
		l.layman.add_js_code ( "news.init ( news.admin.init );" )
	else:
		l.layman.add_js_code ( "news.init ();" )



	return ''


def get ( liwe, id_news ):
	"""
	:INPUT:
		- id_news:              SAFE_NUMBER
	"""

	n = News ( liwe )

	row = n.get ( id_news )
	row [ '_html_tags' ] = ''
	#return { 'news': n.get ( id_news ) }
	return _apply_template ( n, row, "NEWS_SHOW" )

def show ( liwe, group_id = 0, testo = '', pub_date = None, limit = 10 ):
	"""
	:INPUT:
		- group_id:		SAFE_NUMBER
		- testo:                SAFE_DB_STRING
		- pub_date:             SAFE_DATE
	"""

	n = News ( liwe )
	res = ""
	rs = n.search ( testo, pub_date )
	if rs:
		for r in rs:
			res += r [ 'title' ] + "<br/>"

	return res

def list ( liwe, mode = "latest", quant = 3, tags = "", exclude_tags = "", template = "NEWS_BOX", news_list_start = "NEWS_LIST_START", news_list_end = "NEWS_LIST_END", id_categs = '' ):
	quant = int ( quant )

	n = News ( liwe )
	rows = n.list ( mode = mode, quant = quant, tags = tags, exclude_tags = exclude_tags, id_categs = id_categs ) [ 'rows' ]

	res = n.templates [ news_list_start ]
	for row in rows:
		res += _apply_template ( n, row, template )

	res += n.templates [ news_list_end ]
	return res

	
def _apply_template ( n, row, template, full = False ):
	res = ''
	if len ( row [ 'media' ] ):
		media = row [ 'media' ] [ 0 ]
		row [ '_img' ] = media [ 'html' ] % { "_size" : "icon", "_ext" :  '.jpg'  }
	else:
		row [ '_img' ] = ''

	row [ '_HREF_CLICK' ] = n.templates [ '_HREF_CLICK' ] % row
	row [ '_ACTION_CLICK' ] = n.templates [ '_ACTION_CLICK' ] % row
	row [ '_HREF_LIST' ] = n.templates [ '_HREF_LIST' ] % row
	row [ '_ACTION_LIST' ] = n.templates [ '_ACTION_LIST' ] % row

	row [ '_gallery' ] = ''

	row [ '_TAG_LIST' ] = ''
	if len ( row.get ( 'tags', [] ) ):
		tags = []
		for tag in row [ 'tags' ]:
			t = n.templates [ 'NEWS_SHOW_TAG' ] % tag
			tags.append ( n.templates [ 'NEWS_TAG' ] % { '_tag' : t } )

		tag_list = { '_tag_list' : ''.join(tags) }
		if tags : row [ '_TAG_LIST' ] =	n.templates [ 'NEWS_TAG_LIST' ] % tag_list

	res += n.templates [ template ] % defaultdict ( str, row )

	return res
	

def test ( liwe, txt = "testo di prova" ):
	n = News ( liwe )
	return "<pre>%s</pre>" % n.config



